package com.example.administrator.szb.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BasePresenter;
import com.example.administrator.szb.activity.base.MVPBaseActivity;
import com.example.administrator.szb.adapter.WTContentAdapter;
import com.example.administrator.szb.bean.GZBean;
import com.example.administrator.szb.bean.RzBean;
import com.example.administrator.szb.bean.SCBean;
import com.example.administrator.szb.bean.TWBean;
import com.example.administrator.szb.bean.WTXQBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.fragments.askmannager.AskManagerFragment;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.QTLog;
import com.example.administrator.szb.util.SPUtils;
import com.example.administrator.szb.util.ShareUtils;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import dmax.dialog.SpotsDialog;

import static com.example.administrator.szb.R.id.wtxq_swipelayout;

/**
 * Created by D N on 2017/9/21.
 */

public class WTContentActivity  extends MVPBaseActivity {
    private SpotsDialog dialog;
    private View bantouming;
    private TextView bar_title;
    private ImageView right_img;
    private de.hdodenhof.circleimageview.CircleImageView ask_headimg;
    private TextView ask_name;
    private TextView ask_time;
    private TextView ask_guanhzu;
    private TextView ask_titles;
    private TextView ask_content;
    private LinearLayout ll_ask_business;
    private TextView ask_business1;
    private TextView ask_business2;
    private TextView ask_business3;
    private TextView ask_business4;
    private TextView ask_shoucang;
    private TextView ask_huida;
    private EditText wtxq_edit_srhd;
    private TextView wtxq_text_fs;
    private LinearLayout wtxq_text_djsc;
    private ImageView ll_sc_img,right_sc;
    private TextView ll_sc_text;
    private LinearLayout ll_content;
    private FrameLayout frameLayout4;
    private SwipeRefreshLayout zxFragmentSwiperefreshlayout;
    private com.example.administrator.szb.view.MyListView listView;
    WTXQBean wtxqBean;//详情实体类
    int refer_id;
    Activity activity;
    List<WTXQBean.DataBean.RefersBean> list = new ArrayList<>();
    private WTContentAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.askcontent);
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return getWindow().superDispatchTouchEvent(ev);
    }
    @Override
    protected void initView() {
        activity = this;
        initKey();
        right_sc = findViewById(R.id.right_sc);
        right_sc.setVisibility(View.VISIBLE);
        bantouming = findViewById(R.id.bantouming);
        bantouming.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKey(v);
                return true;
            }
        });
        frameLayout4 = findViewById(R.id.frameLayout4);
        bar_title = (TextView) findViewById(R.id.bar_title);
        bar_title.setText("问答详情");
        right_img = (ImageView) findViewById(R.id.right_img);
        //问答top
        ask_headimg = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.ask_headimg);
        ask_name = (TextView) findViewById(R.id.ask_name);
        ask_time = (TextView) findViewById(R.id.ask_time);
        ask_guanhzu = (TextView) findViewById(R.id.ask_guanhzu);
        ask_titles = (TextView) findViewById(R.id.ask_titles);
        ask_content = (TextView) findViewById(R.id.ask_content);
        ll_ask_business = (LinearLayout) findViewById(R.id.ll_ask_business);
        ask_business1 = (TextView) findViewById(R.id.ask_business1);
        ask_business2 = (TextView) findViewById(R.id.ask_business2);
        ask_business3 = (TextView) findViewById(R.id.ask_business3);
        ask_business4 = (TextView) findViewById(R.id.ask_business4);
        ask_shoucang = (TextView) findViewById(R.id.ask_shoucang);
        ask_huida = (TextView) findViewById(R.id.ask_huida);
        //底部发送
        wtxq_edit_srhd = (EditText) findViewById(R.id.wtxq_edit_srhd);
        wtxq_text_fs = (TextView) findViewById(R.id.wtxq_text_fs);
        wtxq_text_djsc = (LinearLayout) findViewById(R.id.wtxq_text_djsc);
        ll_sc_img = (ImageView) findViewById(R.id.ll_sc_img);
        ll_sc_text = (TextView) findViewById(R.id.ll_sc_text);

        ll_content = (LinearLayout) findViewById(R.id.ll_content);
        zxFragmentSwiperefreshlayout = (SwipeRefreshLayout) findViewById(wtxq_swipelayout);
        listView = (com.example.administrator.szb.view.MyListView) findViewById(R.id.listView);
        zxFragmentSwiperefreshlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QTLog.e("aaaaaaaa");
                editTextOut(false);
            }
        });
        wtxq_edit_srhd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QTLog.e("bbbbbbbbb");
                editTextOut(true);
            }
        });
        //wtxq_edit_srhd.focus(false);
        wtxq_edit_srhd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                editTextOut(true);
            }
        });
    }
    private boolean iserror = true;

    @Override
    public void editTextOut(boolean isshow) {
        if (isshow){
            QTLog.e("软键盘弹起");
            bantouming.setVisibility(View.VISIBLE);
            wtxq_edit_srhd.setLines(5);
            //wtxq_text_djsc.setVisibility(View.GONE);
            wtxq_text_fs.setVisibility(View.VISIBLE);
        }else {
            QTLog.e("软键盘关闭");
            bantouming.setVisibility(View.GONE);
            wtxq_edit_srhd.setLines(1);
            wtxq_text_fs.setVisibility(View.GONE);
            //wtxq_text_djsc.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void initEvent() {


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    Intent intent = new Intent(context, HDXQActivity.class);
                    intent.putExtra("image", wtxqBean.getData().getRefers().get(position).getHeadimg() + "");
                    intent.putExtra("refer_id", wtxqBean.getData().getRefers().get(position).getId());
                    intent.putExtra("quiz_id", wtxqBean.getData().getRefers().get(position).getQuiz_id());
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        wtxq_text_fs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onViewClicked(v);
            }
        });
        right_sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onViewClicked(v);
            }
        });
        ask_headimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent_go = new Intent(context, GWCententActivity.class);
                intent_go.putExtra("refer_id", wtxqBean.getData().getQuiz_id());
                startActivity(intent_go);
            }
        });
        ask_guanhzu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onViewClicked(v);
            }
        });
        right_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iserror){
                    return;
                }

                ShareUtils.share(activity, URLAddress.ASK_SHARE_IMG,URLAddress.ASK_SHARE+"?refer_id="+refer_id+"&id="+ SPUtils.getUserId()+"&app=1",wtxqBean.getData().getTitle(),wtxqBean.getData().getContent());

            }
        });
        zxFragmentSwiperefreshlayout.setColorSchemeResources(R.color.zhutise);


        zxFragmentSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                zxFragmentSwiperefreshlayout.setRefreshing(true);
                requestData();
            }
        });
    }

    @Override
    protected void initData() {
        refer_id = getIntent().getIntExtra("refer_id", 0);//获取列表问题的id
        adapter = new WTContentAdapter(context,list);
        listView.setAdapter(adapter);
        zxFragmentSwiperefreshlayout.post(new Runnable() {
            @Override
            public void run() {

                zxFragmentSwiperefreshlayout.setRefreshing(true);
                requestData();
            }
        });
    }

    public void onViewClicked(View view) {
        if (SampleApplicationLike.getUserloginInstance().getId() == 0) {
            startActivity(new Intent(this, LoginNewActivity_two.class));
        } else {
            switch (view.getId()) {/*
                case R.id.ask_headimg:
                    Intent intent_go = new Intent(context, GWCententActivity.class);
                    intent_go.putExtra("refer_id", wtxqBean.getData().getQuiz_id());
                    startActivity(intent_go);
                    //startActivity(new Intent(this,GWCententActivity.class));*//*
                    break;*/
                case R.id.ask_guanhzu:
                    if (wtxqBean.getData().getIs_me() == 1) {
                        new AlertDialog.Builder(context)
                                .setTitle("提示")
                                .setMessage("确认删除？")
                                .setNegativeButton("取消",null)
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        requstDel();//删除操作
                                    }
                                }).show();




                    } else {

                        doRequestGz();//执行关注或者取消关注操作
                    }

                    break;
                case R.id.right_sc:

                    doRequestDjsc();//执行收藏或者取消操作
                    break;
                case R.id.wtxq_text_fs:
                    requestMyAnswer();//执行发送答案
                    break;
            }
        }

    }
    private void requestMyAnswer() {
        QTLog.e("点击率");
        if (TextUtils.isEmpty(wtxq_edit_srhd.getText().toString().trim())) {
            DialogUtil.showSimpleDialog(this, "请输入回答内容！");
        } else {
            dorequestFS();
        }
    }
    /**
     * 显示进度条
     */
    private void showProgressbar() {
        dialog = new SpotsDialog(this, R.style.Custom);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        // WindowManager m = getWindowManager();
//        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
//        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
//        p.height = 300;   //高度设置为屏幕的0.3
//        p.width = 500;    //宽度设置为屏幕的0.5
//        dialog.getWindow().setAttributes(p);
    }

    /**
     * 执行发送请求
     */
    private void dorequestFS() {
        showProgressbar();

        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        if (SampleApplicationLike.getUserloginInstance().getId() != wtxqBean.getData().getQuiz_id()){
            map.put("users_id", wtxqBean.getData().getQuiz_id() + "");
        }else{
            map.put("users_id", 0 + "");
        }
        map.put("content", wtxq_edit_srhd.getText().toString().trim());
        map.put("title", "YXG");
        map.put("business_id", "0");
        map.put("refer_id", wtxqBean.getData().getId() + "");
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, TWBean.class, URLAddress.URLBASE + URLAddress.URL_TW_HD, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                TWBean twBean = (TWBean) response;
                if (twBean.getResult() == 1) {
                    dialog.dismiss();
                    wtxq_edit_srhd.setText("");

                    //DialogUtil.showSimpleDialog(context, "提问成功");
                    finish();
                    Intent intent = new Intent(context, WTContentActivity.class);
                    //SampleApplicationLike.getQueueInstance().cancelAll("tag");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    intent.putExtra("refer_id", refer_id);
                    startActivity(intent);
                    overridePendingTransition(0, 0);

                    // onCreate(null);

                } else {
                    dialog.dismiss();
                    //DialogUtil.showSimpleDialog(context, twBean.getErr_msg());
                    Toasts.show(context, "" + twBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dialog.dismiss();
                Toasts.show(context, "" + error, Toast.LENGTH_SHORT);
                // DialogUtil.showSimpleDialog(context, "服务端异常，请再试一次吧。。。");
            }
        });
    }
    private void doRequestDjsc() {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        // map.put("id","51");
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("refer_id", wtxqBean.getData().getId() + "");
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, SCBean.class, URLAddress.URLBASE + URLAddress.URL_SC, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                SCBean scBean = (SCBean) response;
                if (scBean.getResult() == 1) {
                    //DialogUtil.showSimpleDialog(context, scBean.getData().getMsg());
                    Toasts.show(context, "" + scBean.getData().getMsg(), Toast.LENGTH_SHORT);
                    zxFragmentSwiperefreshlayout.setRefreshing(true);
                    requestData();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.toString();
            }
        });
    }
    private void requestData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        //map.put("id","51");
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("refer_id", refer_id + "");
        //RequestQueue queue = Volley.newRequestQueue(this);//产生一个新的网络队列，这里解决卡顿问题，如果使用application 中的queue会卡。因为发出了很多次请求
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, WTXQBean.class, URLAddress.URLBASE + URLAddress.URL_WT_XQ, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                iserror=false;
                wtxqBean = (WTXQBean) response;
                if (wtxqBean.getResult() == 1) {
                    String str = JSON.toJSONString(wtxqBean.getData());
                    if (TextUtils.isEmpty(str)||str.equals("{}")){
                        iserror = true;
                        // context.findViewById(R.id.frameLayout4_wtcontent).setVisibility(View.VISIBLE);
                        frameLayout4.setVisibility(View.VISIBLE);//移除空白加载
                        ll_content.setVisibility(View.GONE);
                        zxFragmentSwiperefreshlayout.setRefreshing(false);
                        return;
                    }
                    initViews();//渲染页面
                    ll_content.setVisibility(View.VISIBLE);
                    frameLayout4.setVisibility(View.GONE);//移除空白加载
                    zxFragmentSwiperefreshlayout.setRefreshing(false);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                iserror = true;
                // context.findViewById(R.id.frameLayout4_wtcontent).setVisibility(View.VISIBLE);
                frameLayout4.setVisibility(View.VISIBLE);//移除空白加载
                ll_content.setVisibility(View.GONE);
                error.toString();
                zxFragmentSwiperefreshlayout.setRefreshing(false);
            }
        });
    }
    private void initViews(){
        if (wtxqBean.getData().getHeadimg() != null) {
            Glide.with(this).load(wtxqBean.getData().getHeadimg()).error(R.drawable.mrtx).into(ask_headimg);
        }
        ask_name.setText(wtxqBean.getData().getName());
        ask_time.setText(wtxqBean.getData().getCreate_time());
        if (wtxqBean.getData().getAttention() == 0) {
            ask_guanhzu.setText("关注");
        } else {
            ask_guanhzu.setText("已关注");
        }

        if (wtxqBean.getData().getIs_me() == 1) {
            ask_guanhzu.setText("删除");
        }

        ask_titles.setText(wtxqBean.getData().getTitle());
        ask_titles.setSingleLine(false);
        showBusiness(wtxqBean.getData().getBusiness());
        ask_content.setText(wtxqBean.getData().getContent());
        ask_shoucang.setText(wtxqBean.getData().getCollect_count() + "收藏");
        ask_huida.setText(wtxqBean.getData().getAnswer_count() + "回答");
        showShouCang(wtxqBean.getData().getIs_collect());
        list.clear();
        if (wtxqBean.getData().getRefers()!=null){

            list.addAll(wtxqBean.getData().getRefers());
        }
        adapter.notifyDataSetChanged();



    }
    private void showShouCang(int type){
        if (type==0){
            //未收藏
            ll_sc_text.setText("收藏");
            right_sc.setImageResource(R.mipmap.sc_white_no);
        }else {
            //已收藏
            ll_sc_text.setText("已收藏");
            right_sc.setImageResource(R.mipmap.sc_white_yes);
        }
    }
    public void showBusiness(List<WTXQBean.DataBean.BusinessBean> list){
        ll_ask_business.setVisibility(View.VISIBLE);
        ask_business1.setVisibility(View.GONE);
        ask_business2.setVisibility(View.GONE);
        ask_business3.setVisibility(View.GONE);
        ask_business4.setVisibility(View.GONE);
        for (int i=0;i<list.size();i++){
            switch (i){
                case 0:
                    ask_business1.setText(list.get(i).getTitle());
                    ask_business1.setVisibility(View.VISIBLE);
                    break;
                case 1:

                    ask_business2.setText(list.get(i).getTitle());
                    ask_business2.setVisibility(View.VISIBLE);
                    break;
                case 2:

                    ask_business3.setText(list.get(i).getTitle());
                    ask_business3.setVisibility(View.VISIBLE);
                    break;
                case 3:

                    ask_business4.setText(list.get(i).getTitle());
                    ask_business4.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }

    /**
     * 执行关注
     */
    private void doRequestGz() {

        if (!(SPUtils.isLogin())){
            startActivity(new Intent(context,LoginNewActivity_two.class));
            return;
        }
        if (wtxqBean.getData().getQuiz_id()==SPUtils.getUserId()){
            DialogUtil.showToast(context,"不能收藏自己");
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        //int id = SampleApplicationLike.getUserloginInstance().getId();
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("quiz_id", wtxqBean.getData().getQuiz_id() + "");
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, GZBean.class, URLAddress.URLBASE + URLAddress.URL_GZ, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                GZBean gzBean = (GZBean) response;
                if (gzBean.getResult() == 1) {
                    if (gzBean.getData().getCode()==0){
                        ask_guanhzu.setText("关注");
                    }else {
                        ask_guanhzu.setText("已关注");
                    }
                    //DialogUtil.showSimpleDialog(context, gzBean.getData().getMsg());
                    Toasts.show(context, "" + gzBean.getData().getMsg(), Toast.LENGTH_SHORT);
                } else {
                    //DialogUtil.showSimpleDialog(context, gzBean.getErr_msg());
                    Toasts.show(context, "" + gzBean.getErr_msg(), Toast.LENGTH_SHORT);
                    //wtxqTextGz.setText("关注");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.toString();
                // DialogUtil.showSimpleDialog(context, "服务器异常，请重新尝试");
                Toasts.show(context, "发生异常", Toast.LENGTH_SHORT);
            }
        });
    }
    public static boolean canRefresh = false;
    @Override
    protected void onResume() {
        super.onResume();
        if (canRefresh)
            requestData();
    }
    private void requstDel() {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("refer_id", wtxqBean.getData().getId() + "");
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, RzBean.class, URLAddress.URLBASE + URLAddress.URL_DEL_HD, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                RzBean rZBean = (RzBean) response;
                if (rZBean.getResult() == 1) {
                    Toasts.show(context, "删除成功", Toast.LENGTH_SHORT);
                    AskManagerFragment.canRefresh=true;
                    finish();
                } else {
                    Toasts.show(context, "" + rZBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toasts.show(context, "" + error.toString(), Toast.LENGTH_SHORT);
            }
        });
    }

}
